package labox.innovation.gameserver.datatables;

import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javolution.util.FastMap;
import labox.innovation.config.Config;
import labox.innovation.db.PlayerDb;
import labox.innovation.gameserver.model.actor.instance.FuzePcInstance;

/**
 * 服务器启动时把记录的玩家ID对应名称读取出来，用来定位重名角色的判定和通过ID找玩家名等等逻辑
 * 
 * @version $Revision: 1.3.2.2.2.1 $ $Date: 2010/6/7 15:29:18 $
 */
public final class CharNameTable {

	private final Map<String, Long> _chars;

	private static final CharNameTable _instance = new CharNameTable();

	private CharNameTable() {
		_chars = new FastMap<String, Long>();
		if (Config.CACHE_CHAR_NAMES)
			loadAll();
	}

	public static final CharNameTable getInstance() {
		return _instance;
	}

	public final void addName(FuzePcInstance l2PcInstance) {
		if (l2PcInstance != null) {
			addName(l2PcInstance.getName(), l2PcInstance.getObjectId());
		}
	}

	private final void addName(String name, long objId) {
		if (name != null) {
			_chars.put(name, objId);
		}
	}

	public final void removeName(String name) {
		_chars.remove(name);
	}

	public final long getIdByName(String name) {
		if (name == null || name.isEmpty())
			return -1;

		Long id = _chars.get(name);

		if (id != null)
			return id;

		if (Config.CACHE_CHAR_NAMES)
			return -1;

		id = PlayerDb.getIdByName(name);

		if (id > 0) {
			_chars.put(name, id);
			return id;
		}

		return -1; // not found
	}

	public final String getNameById(long id) {
		if (id <= 0)
			return null;

		for (Map.Entry<String, Long> pair : _chars.entrySet()) {
			if (pair.getValue() == id) {
				return pair.getKey();
			}
		}

		if (Config.CACHE_CHAR_NAMES)
			return null;

		String name = PlayerDb.getNameById(id);
		if (name != null && name.length() > 0) {
			_chars.put(name, id);
			return name;
		}

		return null; // not found
	}

	public boolean doesCharNameExist(String name) {
		if (Config.CACHE_CHAR_NAMES) {
			return _chars.containsKey(name);
		} else {
			return PlayerDb.doesCharNameExist(name);
		}
	}

	public int accountCharNumber(String account) {
		return PlayerDb.accountCharNumber(account);
	}

	private void loadAll() {
		PlayerDb.loadAllcharacter(_chars);
	}
}
